const Koa = require('koa');
const Router = require('@koa/router');
const Boom = require('boom');

const app = new Koa();
app.use(require('koa-static')(require('../public').DIR_NAME));

const router = new Router();

function sleep(ms) {
  return new Promise((resolve) => {
    const t = setTimeout(() => {
      resolve();
      clearTimeout(t);
    }, ms);
  });
}

router.get('/file/text.txt', async (ctx) => {
  const line = 'Hello World.  你好。 Konnichiwa. 😁😁😁。心有所向，日复一日，必有精进。\n';
  const count = 80;
  ctx.res.writeHead(200, {
    'Content-Type': 'text/plain',
    'Content-Length': line.length * count,
  });

  for (let i = 0; i < count; i++) {
    await sleep(100)
    ctx.res.write(line);
  }
  ctx.res.end();
  console.log('完成');
});

app.use(router.routes());
app.use(
  router.allowedMethods({
    throw: true,
    notImplemented: () => new Boom.notImplemented(),
    methodNotAllowed: () => new Boom.methodNotAllowed(),
  })
);

app.listen(3000);
